package com.ruoyi.web.controller.system;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginByOtherSourceBody;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SysLoginByOtherSourcesController {

    @Value("${gitee.clientId}")
    private String clientId;

    @Value("${gitee.clientSecret}")
    private String clientSecret;

    @Value("${gitee.redirectUri}")
    private String redirectUri;


    @Autowired
   private SysLoginService loginService;

    @GetMapping("/PreLoginByGitee")
    public AjaxResult PreLoginByGitee() {
        AjaxResult ajax = AjaxResult.success();
        
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .redirectUri(redirectUri)
                .build());
        
        String uuid = IdUtils.fastUUID();
        String authorizeUrl = authRequest.authorize(uuid);
        
        ajax.put("authorizeUrl", authorizeUrl);
        ajax.put("uuid", uuid);
        return ajax;
    }


    @PostMapping("/loginByGitee")
    public AjaxResult loginByGitee(@RequestBody LoginByOtherSourceBody loginByOtherSourceBody) {
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.loginByOtherSource(
                loginByOtherSourceBody.getCode(),
                loginByOtherSourceBody.getSource(),
                loginByOtherSourceBody.getUuid()
        );
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



}